#!/usr/bin/env python
from urllib2 import urlopen
from urllib import urlencode
import sys
from gd import detect_lang

# TODO: update twitter status with many language!
# The google translate API can be found here: 
# http://code.google.com/apis/ajaxlanguage/documentation/#Examples

argv = sys.argv
from_file = False
result_file = None

if len(argv) < 4:
	print 'USAGE:\n%s language_code text'%argv[0]
	print '%s language_code --file file_name'%argv[0]
	sys.exit(1)

del argv[0]

if argv[0] == '--to':
	to_langs = argv[1].split(' ')
	del argv[0:2]

if argv[0] == '--write':
	result_file = argv[1]
	del argv[0:2]

if argv[0] == '--file':
	file_name = argv[1]
	text = open(argv[1], 'r').read()
	from_file = True
	del argv[0:2]
else: text = ' '.join(argv[0:])

paragraphs = text.split('\n')
lang1 = detect_lang(paragraphs[0][:600]) #sys.argv[2]

for lang in to_langs:
	print "Translation in %s is "%lang,
	if from_file: print '\n',
	langpair = '%s|%s'%(lang1,lang)
	base_url = 'http://ajax.googleapis.com/ajax/services/language/translate?'

	translation = ''
	index = 0
	for p in paragraphs:
		cut = False
		index += 1
		if len(p.strip()) < 1: continue
		if len(p) > 680: 
			paragraphs.insert(index, p[680:])
			p = p[:680]
			cut = True
		params = urlencode((('v',1.0), ('q',p),('langpair',langpair)))
		url = base_url + params
		content = urlopen(url).read()
		start_idx = content.find('"translatedText":"')+18
		_translation = content[start_idx:]
		end_idx = _translation.find('"}, "')
		translation += _translation[:end_idx] + '\n'
		if cut: newline = ''
		else: newline = '\n'

		print _translation[:end_idx].replace('\u0026quot;', '"'), newline,
	print '\n',
	
	# Write output to files
	if result_file:
		output_file_name = lang + '_' + result_file
		output_file = open(output_file_name, 'w')
		output_file.write(translation.replace('\u0026quot;', '"'))
		output_file.close()
	
